package rush.edu.wechat.admin.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import rush.edu.wechat.admin.web.dto.UserDto;
import rush.edu.wechat.admin.web.handler.AdminHandler;

import javax.servlet.http.HttpServletRequest;

/**
 * DESC:
 * USER:hmily
 * DATE:2018/1/31
 * TIME:14:03
 */
@Controller
public class AdminController {

    @Autowired
    private AdminHandler adminHandler;

    @RequestMapping("/")
    public String index(){
        return "landing";
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

    @RequestMapping("/admin/doLogin")
    public String doLogin(@RequestParam("email")String email,
                          @RequestParam("password")String password,
                          @RequestParam(value = "rememberMe",defaultValue = "false")Boolean rememberMe,
                          HttpServletRequest request, RedirectAttributes model){

        UserDto userDto = adminHandler.loadUser(email, password, rememberMe);
        request.getSession().setAttribute("token",userDto.getToken());
        model.addFlashAttribute("user",userDto);
        return "redirect:/admin";
    }

    @RequestMapping("/admin")
    public String adminIndex(@ModelAttribute("user") UserDto userDto , Model model){
        model.addAttribute("user",userDto);
        return "admin-index";
    }
}
